package com.zx.sdk.league.member.zhongjian;

import static android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.GeolocationPermissions;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

import androidx.appcompat.app.AlertDialog;

import com.zx.sdk.BuildConfig;
import com.zx.sdk.model.AdInfo;
import com.zx.sdk.util.LogHelper;
import com.zx.sdk.util.UiHelper;
import com.zx.sdk.view.widget.BaseNewsAdView;

public class ZjNewWebView extends BaseNewsAdView {
    private final String NEWS_URL = "https://static.dwodai.cn/html/cnzz/468.html";
    private boolean clearHistory = false;
    private final WebView webView;

    public ZjNewWebView(Context context, AdInfo mAdInfo) {
        super(context, mAdInfo);
        webView = initWebView();
        webView.loadUrl(NEWS_URL);
    }

    private WebView initWebView() {
        WebView mWebView = new WebView(getContext());
        addView(mWebView, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        WebSettings settings = mWebView.getSettings();
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);
        // ZoomControls（就是放大放小按钮） 是个渐变的过程（渐变未完成就destroy）会导致View not attached to window manager
        settings.setDisplayZoomControls(false);
        // 设置定位的数据库路径
        settings.setDatabaseEnabled(true);
        String dir = getContext().getDir("database", Context.MODE_PRIVATE).getPath();
        settings.setGeolocationDatabasePath(dir);
        // 启用地理定位
        settings.setGeolocationEnabled(true);

        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setAllowUniversalAccessFromFileURLs(true);
        settings.setAllowFileAccess(true);
        settings.setMediaPlaybackRequiresUserGesture(false);
        // 设置支持DomStorage
        settings.setDomStorageEnabled(true);
        mWebView.setVerticalScrollBarEnabled(false);
        settings.setMixedContentMode(MIXED_CONTENT_ALWAYS_ALLOW);
        if (BuildConfig.DEBUG) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        settings.setSupportMultipleWindows(false);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        CookieManager.getInstance().setAcceptThirdPartyCookies(mWebView, true);
        ProgressBar progressBar = new ProgressBar(getContext());
        progressBar.setIndeterminate(false);
        addView(progressBar, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, UiHelper.dp2Px(2)));
        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int progress) {
                progressBar.setProgress(progress);
                if (progress < 100) {
                    progressBar.setVisibility(View.VISIBLE);
                } else {
                    progressBar.setVisibility(View.GONE);
                }
            }

            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                new AlertDialog.Builder(getContext())
                    .setMessage(message)
                    .setPositiveButton(android.R.string.yes, (dialog, which) -> result.confirm())
                    .setNegativeButton(android.R.string.cancel, (dialog, which) -> result.cancel())
                    .create()
                    .show();
                return true;
            }
        });
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 自定义协议，跳转交由系统决定
                if (!url.startsWith("http")) {
                    try {
                        final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        view.getContext().startActivity(intent);
                    } catch (Exception e) {
                        LogHelper.e("ZjNewWebView", e);
                    }
                    return true;
                }
                return false;
            }

            @Override
            public void onPageStarted(WebView webView, String url, Bitmap bitmap) {
                if (url.contains("/home/index/")) {
                    listener.onBackToHome();
                } else if (url.contains("/home/artical/")) {
                    listener.onNewsPageStart(url);
                }
            }

            @Override
            public void onPageFinished(WebView webView, String s) {
                progressBar.setVisibility(View.GONE);
                if (clearHistory) {
                    clearHistory = false;
                    mWebView.clearHistory();
                }
            }
        });
        return mWebView;
    }

    @Override
    public void backToHome(boolean clearHistory) {
        this.clearHistory = clearHistory;
        webView.loadUrl(NEWS_URL);
    }

    @Override
    public boolean onBackPressed() {
        if (webView != null && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return false;
    }
}
